package com.yejiali.backend.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * @Author:yejiali
 * @Date:2025/7/21-07-21-16:09
 * @Decsription:com.yejiali.backend.util
 * @Version:1.0
 */
public class UrlUtil {

    /**
     * 验证 URL 格式和协议
     * @param url 待验证的 URL
     * @return 验证结果
     */
    public static boolean isValidUrl(String url) {
        try {
            URL videoUrl = new URL(url);
            //获取URL协议部分
            String protocol = videoUrl.getProtocol();
            //判断格式是否正确
            return "http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证 URL 是否可访问
     * @param url 待验证的 URL
     * @return 验证结果
     */
    public static boolean isUrlReachable(String url) {
        try {
            //根据URL创建连接对象
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            //设置请求方法为HEAD,与GTE的区别在于这个方法只返回响应头
            connection.setRequestMethod("HEAD");
            //获取响应码
            int responseCode = connection.getResponseCode();
            return (responseCode >= 200 && responseCode < 400);
        } catch (Exception e) {
            return false;
        }
    }
    }
